/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package character_11_;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.Executor;

/**
 *
 * @author Administrator
 */
public class Pages {
    
    private URL[] urls;
    private String[] fileNames;
    private Executor executor;

    public Pages(URL[] urls, String[] fileNames, Executor executor ) {
        this.urls = urls;
        this.fileNames = fileNames;
        this.executor = executor;
    }
    
    public void download(){
    
        for (int i = 0; i < urls.length; i++) {
        
            URL url = urls[i];
            String fileName = fileNames[i];
            executor.execute(() -> {
            
                try {
                    dump(url.openStream(), new FileOutputStream(fileName));
                } catch (IOException e) {
                    throw new RuntimeException();
                }
            });
        }
    }
    
    void dump(InputStream src, OutputStream dest) {

		try (InputStream input = src; OutputStream output = dest;) {
			byte[] data = new byte[1024];
			int length;
			while ((length = input.read(data)) != -1) {
				output.write(data, 0, length);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
